package com.nanhu.sms;

import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

public class SmsListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>{
	
	final static String SMS_URI_ALL = "content://sms/";
	final static String SMS_URI_INBOX = "content://sms/inbox";
	final static String SMS_URI_SEND = "content://sms/sent";
	final static String SMS_URI_DRAFT = "content://sms/draft";
	final static String SMS_URI_OUTBOX = "content://sms/outbox";
	final static String SMS_URI_FAILED = "content://sms/failed";
	final static String SMS_URI_QUEUED = "content://sms/queued";
	
	// This is the Adapter being used to display the list's data.
    SimpleCursorAdapter mAdapter;

	// If non-null, this is the current filter the user has provided.
    String mCurFilter;
	
	// These are the Contacts rows that we will retrieve.
    static String[] projection = new String[]{"_id", "address", "person", "body", "date", "type"};
    
    private int type;
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
    	super.onActivityCreated(savedInstanceState);
    	Bundle arguments = this.getArguments();
    	type = arguments.getInt("type");
    	// Give some text to display if there is no data.  In a real
        // application this would come from a resource.
        // We have a menu item to show in action bar.
        setHasOptionsMenu(true);
        // Create an empty adapter we will use to display the loaded data.
        mAdapter = new MySimpleCursorAdapter(getActivity(),
                android.R.layout.simple_list_item_2, null,
                new String[] { "date", "body"},
                new int[] { android.R.id.text1, android.R.id.text2}, 0);
        setListAdapter(mAdapter);
        // Start out with a progress indicator.
        setListShown(false);
        // Prepare the loader.  Either re-connect with an existing one,
        // or start a new one.
        getLoaderManager().initLoader(0, null, this);
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    	super.onCreateOptionsMenu(menu, inflater);
    	MenuItem item = menu.add(0, 0, 1, "新建");
        item.setIcon(android.R.drawable.ic_menu_add);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()){
	    	case 0:
	    		Intent intent = new Intent(getActivity(), SmsSendActivity.class);
	    		startActivity(intent);
	    		break;
    	}
    	return true;
    }
    
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
    	Intent intent = new Intent(this.getActivity(), SmsViewActivity.class);
    	intent.putExtra("id", id);
    	startActivity(intent);
    }
	
	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
        Uri baseUri;
        switch(type){
	        case 1:
	        	baseUri = Uri.parse(SMS_URI_INBOX);
	        	setEmptyText("收信箱为空");
	        	break;
	        case 2:
	        	baseUri = Uri.parse(SMS_URI_SEND);
	        	setEmptyText("发信箱为空");
	        	break;
	        case 3:
	        	baseUri = Uri.parse(SMS_URI_DRAFT);
	        	setEmptyText("草稿箱为空");
	        	break;
        	default:
        		baseUri = Uri.parse(SMS_URI_ALL);
        		setEmptyText("信箱为空");
        }
        // Now create and return a CursorLoader that will take care of
        // creating a Cursor for the data being displayed.
        return new CursorLoader(getActivity(), baseUri, projection, null, null, "date COLLATE LOCALIZED desc");
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        // Swap the new cursor in.  (The framework will take care of closing the
        // old cursor once we return.)
        mAdapter.swapCursor(data);

        // The list should now be shown.
        if (isResumed()) {
            setListShown(true);
        } else {
            setListShownNoAnimation(true);
        }
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		mAdapter.swapCursor(null);
	}
	
	class MySimpleCursorAdapter extends SimpleCursorAdapter{

		public MySimpleCursorAdapter(Context context, int layout, Cursor c,
				String[] from, int[] to, int flag) {
			super(context, layout, c, from, to, flag);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			TextView title = (TextView)view.findViewById(android.R.id.text1);
			
			Cursor c = getCursor();
			long lDate = c.getLong(c.getColumnIndex("date"));
			Date date = new Date(lDate);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			String sDate = sdf.format(date);
			
			title.setText(sDate);
			return view;
		}
	}
	
}
